﻿using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using ImageTools.IO.Gif;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyDeeWeibo.Classes;

namespace MyDeeWeibo.PageViews
{
    public partial class Discoverys : PhoneApplicationPage
    {
        #region DependencyProperties

        #region PublicTimelineListProperty
        public static readonly DependencyProperty PublicTimelineListProperty =
            DependencyProperty.Register(
            "PublicTimelineList",
            typeof(ObservableCollection<WStatus>),
            typeof(Discoverys),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> PublicTimelineList
        {
            get { return (ObservableCollection<WStatus>)GetValue(PublicTimelineListProperty); }
            set { SetValue(PublicTimelineListProperty, value); }
        }
        #endregion

        #region HotRepostDailyProperty
        public static readonly DependencyProperty HotRepostDailyProperty =
            DependencyProperty.Register(
            "HotRepostDaily",
            typeof(ObservableCollection<WStatus>),
            typeof(Discoverys),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> HotRepostDaily
        {
            get { return (ObservableCollection<WStatus>)GetValue(HotRepostDailyProperty); }
            set { SetValue(HotRepostDailyProperty, value); }
        }
        #endregion

        #region HotCommentDailyProperty
        public static readonly DependencyProperty HotCommentDailyProperty =
            DependencyProperty.Register(
            "HotCommentDaily",
            typeof(ObservableCollection<WStatus>),
            typeof(Discoverys),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> HotCommentDaily
        {
            get { return (ObservableCollection<WStatus>)GetValue(HotCommentDailyProperty); }
            set { SetValue(HotCommentDailyProperty, value); }
        }
        #endregion

        #region HotRepostWeeklyProperty
        public static readonly DependencyProperty HotRepostWeeklyProperty =
            DependencyProperty.Register(
            "HotRepostWeekly",
            typeof(ObservableCollection<WStatus>),
            typeof(Discoverys),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> HotRepostWeekly
        {
            get { return (ObservableCollection<WStatus>)GetValue(HotRepostWeeklyProperty); }
            set { SetValue(HotRepostWeeklyProperty, value); }
        }
        #endregion

        #region HotCommentWeeklyProperty
        public static readonly DependencyProperty HotCommentWeeklyProperty =
            DependencyProperty.Register(
            "HotCommentWeekly",
            typeof(ObservableCollection<WStatus>),
            typeof(Discoverys),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> HotCommentWeekly
        {
            get { return (ObservableCollection<WStatus>)GetValue(HotCommentWeeklyProperty); }
            set { SetValue(HotCommentWeeklyProperty, value); }
        }
        #endregion

        #region ProgressIndicatorIsVisibleProperty
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
            DependencyProperty.Register("ProgressIndicatorIsVisible",
            typeof(bool),
            typeof(Discoverys),
            new PropertyMetadata(false));

        public bool ProgressIndicatorIsVisible
        {
            get { return (bool)GetValue(ProgressIndicatorIsVisibleProperty); }
            set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
        }
        #endregion

        #endregion

        #region DefineVariables
        private DeeCmdBase cmdBase;
        private DeeNetEngine netEngine;

        public WStatus sStatusShow; //传递微博id

        //动态刷新页面
        public bool pivot0;
        public bool pivot1;
        public bool pivot2;
        public bool repost_daily_weekly;
        public bool comment_daily_weekly;

        private ScrollViewer myScrollViewer = null;

        public string refresh_page;

        #endregion

        private void RefreshPublicTimeline()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "30"
                //page = refresh_page
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.PUBLIC_TIMELINE, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatuses ptimeliststatuses = null;
                        try
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WStatuses));
                            ptimeliststatuses = ser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            PublicTimelineList = new ObservableCollection<WStatus>(ptimeliststatuses.statuses);
#if sample
                            if (PublicTimelineList == null)
                            {
                                PublicTimelineList = new ObservableCollection<WStatus>(ptimeliststatuses.statuses);
                            }
                            else
                            {
                                if (ptimeliststatuses.statuses.Length != 0 && PublicTimelineList != null)
                                {
                                    for (int i = 0; i < ptimeliststatuses.statuses.Length; i++)
                                        PublicTimelineList.Add(ptimeliststatuses.statuses[i]);
                                    if (myScrollViewer != null)
                                    {
                                        if (myScrollViewer.VerticalOffset != 0)
                                        {
                                            ScrollViewer toBottomScrollViewer = myScrollViewer;
                                            toBottomScrollViewer.ScrollToVerticalOffset(toBottomScrollViewer.VerticalOffset * 1.1);
                                        }
                                    }
                                }
                            }
#endif
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void RefreshHotRepostDaily()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "30"
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.HOT_REPOSTS_DAILY, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatus[] hotreposttatuses = null;
                        try
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WStatus[]));
                            hotreposttatuses = ser.ReadObject(response.stream) as WStatus[];
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            HotRepostDaily = new ObservableCollection<WStatus>(hotreposttatuses);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void RefreshHotCommentDaily()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "30"
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.HOT_COMMENTS_DAILY, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatus[] hotcommenttatuses = null;
                        try
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WStatus[]));
                            hotcommenttatuses = ser.ReadObject(response.stream) as WStatus[];
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            HotCommentDaily = new ObservableCollection<WStatus>(hotcommenttatuses);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void RefreshHotRepostWeekly()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "30"
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.HOT_REPOSTS_WEEKLY, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatus[] hotreposttatuses = null;
                        try
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WStatus[]));
                            hotreposttatuses = ser.ReadObject(response.stream) as WStatus[];
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            HotRepostWeekly = new ObservableCollection<WStatus>(hotreposttatuses);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void RefreshHotCommentWeekly()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "30",
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.HOT_COMMENTS_WEEKLY, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatus[] hotcommenttatuses = null;
                        try
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WStatus[]));
                            hotcommenttatuses = ser.ReadObject(response.stream) as WStatus[];
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            HotCommentWeekly = new ObservableCollection<WStatus>(hotcommenttatuses);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        //data to another xaml
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            WeiboContent StatusShow = e.Content as WeiboContent;
            if (StatusShow != null)
            {
                StatusShow.StatusResults = sStatusShow;
                hotReposts.SelectedItem = null;
                hotComments.SelectedItem = null;
                randomStatuses.SelectedItem = null;
                hotRepostsWeek.SelectedItem = null;
                hotCommentsWeek.SelectedItem = null;
            }
        }

        public Discoverys()
        {
            pivot0 = true;
            pivot1 = true;
            pivot2 = true;
            repost_daily_weekly = true;
            comment_daily_weekly = true;
            //refresh_page = "1";
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.ProgressIndicator = new ProgressIndicator();
            SystemTray.ProgressIndicator.Text = "数据传输中";

            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData.Source = this;
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsVisibleProperty, bindingData);
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsIndeterminateProperty, bindingData);

            ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
        }

        private void MainPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (MainPivot.SelectedIndex)
            {
                case 0:
                    {
                        if (pivot0 == true)
                        {
                            RefreshHotRepostDaily();
                            RepostDailyButton.IsChecked = true;
                        }
                        pivot0 = false;
                    }
                    break;
                case 1:
                    {
                        if (pivot1 == true)
                        {
                            RefreshHotCommentDaily();
                            CommentDailyButton.IsChecked = true;
                        }
                        pivot1 = false;
                    }
                    break;
                case 2:
                    {
                        if (pivot2 == true)
                        {
                            RefreshPublicTimeline();
                        }
                        pivot2 = false;
                    }
                    break;
                default:
                    {

                    }
                    break;
            }
        }

        private void hotReposts_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            sStatusShow = (sender as ListBox).SelectedItem as WStatus;
            if (sStatusShow != null)
            {
                NavigationService.Navigate(new Uri("/PageViews/WeiboContent.xaml", UriKind.Relative));
            }
        }

        private void hotComments_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            sStatusShow = (sender as ListBox).SelectedItem as WStatus;
            if (sStatusShow != null)
            {
                NavigationService.Navigate(new Uri("/PageViews/WeiboContent.xaml", UriKind.Relative));
            }
        }

        private void randomStatuses_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            sStatusShow = (sender as ListBox).SelectedItem as WStatus;
            if (sStatusShow != null)
            {
                NavigationService.Navigate(new Uri("/PageViews/WeiboContent.xaml", UriKind.Relative));
            }
        }

        private void toTopButtonRe_Click(object sender, RoutedEventArgs e)
        {

        }

        private void toTopButtonCo_Click(object sender, RoutedEventArgs e)
        {

        }

        private void UserSettings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PageViews/UserSettings.xaml", UriKind.Relative));
        }

        private void refreshIconButton_Click(object sender, EventArgs e)
        {

        }

        private void ListBox_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            switch (MainPivot.SelectedIndex)
            {
                case 0:
                    {
                        
                    }
                    break;
                case 1:
                    {
                        
                    }
                    break;
                case 2:
                    {
                        myScrollViewer = sender as ScrollViewer;
                        if (e.TotalManipulation.Translation.Y < 0 && myScrollViewer.VerticalOffset > (myScrollViewer.ScrollableHeight - 1))
                        {
                            refresh_page = (Convert.ToInt64(refresh_page, 10) + 1).ToString();
                            RefreshPublicTimeline();
                        }
                    }
                    break;
                default:
                    {

                    }
                    break;
            }
        }

        private void RepostDailyButton_Click(object sender, RoutedEventArgs e)
        {
            hotReposts.Visibility = Visibility.Visible;
            hotRepostsWeek.Visibility = Visibility.Collapsed;
        }

        private void RepostWeeklyButton_Click(object sender, RoutedEventArgs e)
        {
            if (repost_daily_weekly == true)
            {
                RefreshHotRepostWeekly();
                repost_daily_weekly = false;
            }
            hotRepostsWeek.Visibility = Visibility.Visible;
            hotReposts.Visibility = Visibility.Collapsed;
        }

        private void CommentDailyButton_Click(object sender, RoutedEventArgs e)
        {
            hotComments.Visibility = Visibility.Visible;
            hotCommentsWeek.Visibility = Visibility.Collapsed;
        }

        private void CommentWeeklyButton_Click(object sender, RoutedEventArgs e)
        {
            if (comment_daily_weekly == true)
            {
                RefreshHotCommentWeekly();
                comment_daily_weekly = false;
            }
            hotCommentsWeek.Visibility = Visibility.Visible;
            hotComments.Visibility = Visibility.Collapsed;
        }

        private void hotRepostsWeek_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            sStatusShow = (sender as ListBox).SelectedItem as WStatus;
            if (sStatusShow != null)
            {
                NavigationService.Navigate(new Uri("/PageViews/WeiboContent.xaml", UriKind.Relative));
            }
        }

        private void hotCommentsWeek_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            sStatusShow = (sender as ListBox).SelectedItem as WStatus;
            if (sStatusShow != null)
            {
                NavigationService.Navigate(new Uri("/PageViews/WeiboContent.xaml", UriKind.Relative));
            }
        }
    }
}